﻿using System;
using System.Collections;
using System.Collections.Generic;
using MGFramework;
using UnityEngine;
using UnityEngine.UI;

/*
 * Author:  hammer
 * CreateTime: 2018/9/30 16:32:34
 * Module: 
 * 主要功能：ui demmo
 *
 */
namespace MGAudioEngine
{

    public class UIDemo : MonoBehaviour
    {

        private bool _isReferenced = false;
        private Button _btnJoinRoom, _btnCreatRoom, _btnQuitRoom, _btnDeallocAudioEngin,
            _btnOpenMic, _btnCloseMic, _btnOpenSpeaker, _btnCloseSpeaker, _btnSend, _btnAuth;
        private InputField _inputChat, _inputRoomId;
        private Text _contentText;
        private string _userName = "unity agent";
        private long _currRoomId = 0;
        void Awake()
        {
            ReferenceView();
        }


        // Use this for initialization
        void Start()
        {
            //inti console
            MGConsole.Instance.Init();
            //open log
            Debuger.EnableLog = true;

            //add listener
            MGAudioEngine.Instance.OnAuthenFail += OnAuthenFail;
            MGAudioEngine.Instance.OnAuthenSuccess += OnAuthenSuccess;
            MGAudioEngine.Instance.OnJoinRoomSuccess += OnJoinRoomSuccess;
            MGAudioEngine.Instance.OnJoinRoomFail += OnJoinRoomFail;
            MGAudioEngine.Instance.OnQuitRoomSuccess += OnQuitRoomSuccess;
            MGAudioEngine.Instance.OnReceiveChatMessage += OnReceiveChatMessage;
            MGAudioEngine.Instance.OnReceiveInfoMessage += OnReceiveInfoMessage;
            MGAudioEngine.Instance.OnConnectStateChanged += OnConnectStateChanged;
            MGAudioEngine.Instance.OnConnectLost += OnConnectLost;
            MGAudioEngine.Instance.OnUpdateSpeakerInfo += OnUpdateSpeakerInfo;
            MGAudioEngine.Instance.OnUserJoinedChannel += OnUserJoinedChannel;

            //random username
#if UNITY_IOS
            _userName = "unity_iOS" + DateTime.Now.Ticks;
#elif UNITY_ANDROID
             _userName = "unity_Android"+DateTime.Now.Ticks;
#endif

        }

        // Update is called once per frame
        void Update()
        {
            MGAudioEngine.Instance.Polling();
        }
        void ReferenceView()
        {
            if (_isReferenced)
                return;

            this._btnJoinRoom        = transform.Find("Btn_JoinRoom").GetComponent<Button>();
            this._btnCreatRoom       = transform.Find("Btn_CreatRoom").GetComponent<Button>();
            this._btnQuitRoom        = transform.Find("Btn_QuitRoom").GetComponent<Button>();
            this._btnDeallocAudioEngin = transform.Find("Btn_DeallocAudioEngin").GetComponent<Button>();
            this._btnOpenMic         = transform.Find("Btn_OpenMic").GetComponent<Button>();
            this._btnCloseMic        = transform.Find("Btn_CloseMic").GetComponent<Button>();
            this._btnOpenSpeaker     = transform.Find("Btn_OpenSpeaker").GetComponent<Button>();
            this._btnCloseSpeaker    = transform.Find("Btn_CloseSpeaker").GetComponent<Button>();
            this._btnSend            = transform.Find("Btn_Send").GetComponent<Button>();
            this._inputChat          = transform.Find("Input_Chat").GetComponent<InputField>();
            this._contentText        = transform.Find("Panel/Text").GetComponent<Text>();
            this._inputRoomId        = transform.Find("Input_RoomId").GetComponent<InputField>();
            this._btnAuth            = transform.Find("Btn_Auth").GetComponent<Button>(); 

            this._btnJoinRoom.onClick.AddListener(OnClickJoinRoom);
            this._btnCreatRoom.onClick.AddListener(OnClickCreateRoom);
            this._btnQuitRoom.onClick.AddListener(OnClickQuitRoom);
            this._btnDeallocAudioEngin.onClick.AddListener(OnClickDeallocEngine);
            this._btnOpenMic.onClick.AddListener(OnClickOpenMic);
            this._btnCloseMic.onClick.AddListener(OnClickCloseMic);
            this._btnOpenSpeaker.onClick.AddListener(OnClickOpenSpeaker);
            this._btnCloseSpeaker.onClick.AddListener(OnClickCloseSpeaker);
            this._btnSend.onClick.AddListener(OnClickSendText);
            this._btnAuth.onClick.AddListener(OnCliclAuth);

            this._inputRoomId.text = _currRoomId.ToString();

            _isReferenced = true;
        }
#region UI

        void OnClickJoinRoom()
        {
            if (!IsAuthted())
                return;
            if (string.IsNullOrEmpty(_inputRoomId.text))
            {
                Debuger.Log("请输入roomId");
                ConsoleLog("请先完成app授权");
                return;
            }
            long roomId;
            if (long.TryParse(_inputRoomId.text, out roomId))
            {
                _currRoomId = roomId;
                MGAudioEngine.Instance.JoinRoom(_currRoomId, _userName);
            }
        }

        void OnClickCreateRoom()
        {
            if (!IsAuthted())
                return;
            MGAudioEngine.Instance.CreateRoom(_userName);
        }

        void OnClickQuitRoom()
        {
            if (!IsAuthted())
                return;
            MGAudioEngine.Instance.QuitRoom(_currRoomId);
        }

        void OnClickDeallocEngine()
        {
            MGAudioEngine.Instance.DeallocMGAudio();
        }

        void OnClickOpenMic()
        {
            if (!IsAuthted())
                return;
            MGAudioEngine.Instance.OpenMic();
        }
        void OnClickCloseMic()
        {
            if (!IsAuthted())
                return;
            MGAudioEngine.Instance.CloseMic();
        }
        void OnClickOpenSpeaker()
        {
            if (!IsAuthted())
                return;
            MGAudioEngine.Instance.OpenSpeaker();
        }
        void OnClickCloseSpeaker()
        {
            if (!IsAuthted())
                return;
            MGAudioEngine.Instance.CloseSpeaker();
        }

        void OnClickSendText()
        {
            if (!IsAuthted())
                return;
            if (string.IsNullOrEmpty(_inputChat.text))
            {
                ConsoleLog("send chat 不能为空");
                return;
            }
            MGAudioEngine.Instance.SendTextMessage(_inputChat.text);
        }

        void OnCliclAuth(){
            //app auth
            MGAudioEngine.Instance.AuthApp("123", "123", "123");
        }


#endregion

#region CallBack

        void OnAuthenFail()
        {
            ConsoleLog("auth fail");
        }

        void OnAuthenSuccess()
        {
            ConsoleLog("auth success");
        }

        void OnJoinRoomSuccess(long roomId)
        {
            ConsoleLog("join room  success "+roomId);
            _inputRoomId.text = roomId.ToString();
        }

        void OnJoinRoomFail(ConnectError connectError)
        {
            ConsoleLog("join room  fail,error: " + connectError.ToString());
        }

        void OnQuitRoomSuccess()
        {
            ConsoleLog("quit room  succes,error: ");
        }

        void OnReceiveChatMessage(ChatMessage chatMessage)
        {
            ConsoleLog(string.Format("rec chatMsg userId:{0}  userName:{1},msg:{2}", chatMessage.userId,chatMessage.userName,chatMessage.body));
        }

        void OnReceiveInfoMessage(InfoMessage infoMessage)
        {
            ConsoleLog("rec infoMsg: " + infoMessage.body);
        }

        void OnConnectStateChanged(ConnectState newState,ConnectState oldState)
        {
            ConsoleLog("rec new state:" + newState.ToString());
        }

        void OnConnectLost(ConnectError connectError)
        {
            ConsoleLog("connectError:" + connectError.ToString());
        }

        void OnUpdateSpeakerInfo(SpeakerInfo speakerInfo)
        {
            ConsoleLog(string.Format("userId:{0} userName:{1} speakState:{2}", speakerInfo.userId,speakerInfo.userName, speakerInfo.talkState));
        }

        void OnUserJoinedChannel(UserChannel userChannel)
        {
            ConsoleLog(string.Format("[OnUserJoinedChannel] userId:{0} userName:{1} newChannelId:{2}", userChannel.userId, userChannel.userName, userChannel.newChannelId));
        }

#endregion

#region Utils

        private void ConsoleLog(string msg)
        {
            this._contentText.text = this._contentText.text + "\r\n" + msg;
        }

        private bool IsAuthted(){
            if (MGAudioEngine.Instance.GetConnectState == ConnectState.UnAuthenticatiion)
            {
                ConsoleLog("请先完成app授权");
                return false;
            }
            return true;
        }

#endregion
    }
}

